package edu.metrostate.capstonediner;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;

public class GameTexture {
	protected String filename;
	protected AssetManager assetManager;
	protected GL10 gl;
	// Stores the  
	protected int textureID;
	// Stores the width of the texture
	protected float width;
	// Stores the height of the texture
	protected float height;

	public GameTexture(AssetManager assetManager, GL10 gl, String filename) {
		this.filename = filename;
		this.assetManager = assetManager;
		this.gl = gl;
		loadTexture();
	}

	private void loadTexture() {
		try {
			// Loads texture from file to system memory
			InputStream inputStream = assetManager.open(filename);
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			
			width = bitmap.getWidth();
			height = bitmap.getHeight();
			
			// Allocates ID for texture
			int textureIDs[] = new int[1];
			gl.glGenTextures(1, textureIDs, 0);
			textureID = textureIDs[0];
			
			// Loads texture into video memory
			gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
			GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
			
			// Sets texture filtering
			gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
			gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
			
			gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
			
			// Unloads texture from system memory;
			bitmap.recycle();
		} catch (IOException ex) {
			Log.d("TexturedTriangleText", "couldn't load asset '" + filename + "'!");
			throw new RuntimeException("couldn't load asset '" + filename + "'");
		}
	}
	
	public void unloadTexture() {
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
		int[] textureIDs = {textureID};
		gl.glDeleteTextures(1, textureIDs, 0);
	}
	
	public void bind() {
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
	}
}
